//
//  DiaryViewController.swift
//  MoodDiary
//
//  Created by OVIX on 2021/1/4.
//

import UIKit

class DiaryViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    var diaryDic: [String: [String: [[String: Any]]]]?
    
    let currentYear: String = NSString.currentYear()
    var lastYear = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        lastYear = "\((Int(currentYear) ?? 1) - 1)"
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "DiaryMonthCell", bundle: .main), forCellReuseIdentifier: "DiaryMonthCell")
        let footerView = Bundle.main.loadNibNamed("DiaryOCFooterView", owner: self, options: nil)?.last as! DiaryOCFooterView
        footerView.frame = CGRect(x: 0, y: 0, width: screen_width, height: 100.0)
        tableView.tableFooterView = footerView
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        loadData()
    }
    
}

extension DiaryViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { 2 }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 12 }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let month = (indexPath.row + 1) % 12
        
        let thisYear = indexPath.section == 0 ? currentYear : lastYear
        
        let thisYearDic = diaryDic?[thisYear]
        let thisMonthArr = thisYearDic?[String(format: "%02d", month)]
        
        let rowHeight: CGFloat = 200.0
        return CGFloat(thisMonthArr?.count ?? 0) * rowHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: DiaryMonthCell = tableView.dequeueReusableCell(withIdentifier: "DiaryMonthCell") as! DiaryMonthCell
        
        let month = (indexPath.row + 1) % 12
        
        let thisYear = indexPath.section == 0 ? currentYear : lastYear
        
        let thisYearDic = diaryDic?[thisYear]
        let thisMonthArr = thisYearDic?[String(format: "%02d", month)]
        
        cell.diaryArr = thisMonthArr
        
        return cell
        
    }
    
}

extension DiaryViewController {
    
    func loadData() {
        
        diaryDic = [
            currentYear: [
            "01":[],
            "02":[],
            "03":[],
            "04":[],
            "05":[],
            "06":[],
            "07":[],
            "08":[],
            "09":[],
            "10":[],
            "11":[],
            "12":[]
        ],
        lastYear: [
            "01":[],
            "02":[],
            "03":[],
            "04":[],
            "05":[],
            "06":[],
            "07":[],
            "08":[],
            "09":[],
            "10":[],
            "11":[],
            "12":[]
        ]
        ]
        
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let diaryFilePath = docPath + "/diary.plist"
        let diaryArr = NSMutableArray(contentsOfFile: diaryFilePath)
        
        guard diaryArr != nil && diaryArr?.count ?? 0 > 0 else {
            tableView.isHidden = true
            return
        }
        
        tableView.isHidden = false
        
        for index in 0..<(diaryArr?.count ?? 0) {
            let dic: [String: Any] = diaryArr?[index] as! [String : Any]
            print(dic)
            
            let timeStampStr: String = dic["timeStampStr"] as! String
            let dicYear = NSString.getYear(timeStampStr)
            let dicMonth = NSString.getMonth(timeStampStr)
            
            if dicYear == currentYear {
                var currentYearDic: [String: [[String: Any]]] = diaryDic?[currentYear] ?? [:]
                var currentMonthArr = currentYearDic[dicMonth]
                currentMonthArr?.append(dic)
                currentYearDic[dicMonth] = currentMonthArr
                diaryDic?[currentYear] = currentYearDic
            } else if dicYear == lastYear {
                
            }
            
        }
        
        tableView.reloadData()
        print("diaryDic === \(diaryDic)")
        
    }
    
}
